package com.qinbaokeji.checkpoint.dahuacamera.config;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.qinbaokeji.checkpoint.dahuacamera.entity.DataSourceEntity;
import com.qinbaokeji.checkpoint.dahuacamera.utils.AESUtil;
import com.zaxxer.hikari.HikariDataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;

import javax.sql.DataSource;
import java.io.BufferedReader;
import java.io.FileReader;

@Configuration
public class JdbcConfig {

    private static final String KEY = "qbkj8888qbkj8888";
    private static final String LICENSEPATH = "license";

    @Autowired
    private SystemConfig systemConfig;
    @Autowired
    private ApplicationArguments applicationArguments;

    @Bean
    public DataSource dataSource() throws Exception {
        String path;
        if(StringUtils.isEmpty(systemConfig.getPath())){
            path = applicationArguments.getNonOptionArgs().get(1)+LICENSEPATH;
        }else{
            path = systemConfig.getPath()+LICENSEPATH;
        }
        BufferedReader in = new BufferedReader(new FileReader(path));
        String str;
        StringBuilder stringBuilder = new StringBuilder();
        while ((str = in.readLine()) != null) {
            stringBuilder.append(str);
        }
        String js = AESUtil.Decrypt(stringBuilder.toString(),KEY);
        DataSourceEntity dataSourceEntity = JSON.toJavaObject(JSONObject.parseObject(js),DataSourceEntity.class);
        HikariDataSource dataSource = new HikariDataSource();
        dataSource.setJdbcUrl(dataSourceEntity.getUrl());
        dataSource.setDriverClassName(dataSourceEntity.getDriverClassName());
        dataSource.setUsername(dataSourceEntity.getUsername());
        dataSource.setPassword(dataSourceEntity.getPassword());
        return dataSource;
    }

    public static void main(String[] args) throws Exception {
        DataSourceEntity dataSourceEntity = new DataSourceEntity();
        dataSourceEntity.setUrl("jdbc:mysql://localhost:3306/checkpoint?serverTimezone=Asia/Shanghai&characterEncoding=utf8&useSSL=false");
        dataSourceEntity.setDriverClassName("com.mysql.cj.jdbc.Driver");
        dataSourceEntity.setUsername("root");
        dataSourceEntity.setPassword("123456");
        String jsonObject = JSONObject.toJSON(dataSourceEntity).toString();
        System.out.println(jsonObject);
        System.out.println(AESUtil.Encrypt(jsonObject,KEY));
    }

}
